import app from '../../package.json';

// 上报API
const API = 'http://log-data.movtile.com/';
const _ua = navigator.userAgent.toLowerCase();

// 事件地址
const PATH = {
  PV: 'pv.jpg',
  VV: 'vv.jpg',
};

const _setLocal = (key, value) => {
  localStorage.setItem(key, encodeURIComponent(value));
};

/**
 * @desc 发送前初始化
 * @private
 */
const _sendBefore = () => {
  let refreshInfo = {};
  // 平台 有课
  refreshInfo.pt = 'kt';
  refreshInfo.os = 'pc';
  refreshInfo.ver = app && app.version;

  refreshInfo.uuid = localStorage.getItem('uuid');
  refreshInfo.href = window.location.pathname;

  // 检查 device_unique_id
  if (!localStorage.getItem('device_unique_id')) {
    _setLocal('device_unique_id', _createDUI());
    refreshInfo.refresh_device_unique_id = true;
  }
  // 设备ID
  refreshInfo.did = localStorage.getItem('device_unique_id');

  return refreshInfo;
};
/**
 * @desc 生成 device unique id，实际上就是 UUID
 */
const _createDUI = () => {
  let d = new Date().getTime();
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    let r = (d + Math.random() * 16) % 16 | 0;
    return (c == 'x' ? r : (r & 0x7) | 0x8).toString(16);
  });
};
/**
 * @desc 是否为对象
 * @param a 任意值
 * @private
 */
const _isObject = (a) => {
  return Object.prototype.toString.call(a) === '[object Object]';
};

/**
 * @desc 格式化数据
 * @param info 发送数据
 * @private
 */
const _formatInfo = (info) => {
  let o = '?';

  for (let k in info) {
    let v = _isObject(info[k]) ? JSON.stringify(info[k]) : info[k];
    if (v) {
      o += `${k}=${encodeURIComponent(v)}&`;
    }
  }

  return o.substring(0, o.length - 1);
};

/**
 * @desc 通过图片发送
 * @param formatedInfo 参数
 * @private
 */
const _sendByImage = (type, formatedInfo) => {
  let sender = new Image();
  sender.onload = () => {};
  sender.onerror = () => {};
  const isDev = process.env.NODE_ENV === 'development';
  if (isDev) {
    sender.src = `${API}dev/${PATH[type]}${formatedInfo}`;
  } else {
    sender.src = `${API}${PATH[type]}${formatedInfo}`;
  }
};

/**
 * @desc 发送信息
 * @param type 业务类型
 * @param info 业务信息
 * @private
 */
const _baseSend = (type, info) => {
  let refreshInfo = _sendBefore();
  let filteredInfo = info;
  filteredInfo.timestamp = +new Date();
  filteredInfo = Object.assign(refreshInfo, filteredInfo);
  _sendByImage(type.toUpperCase(), _formatInfo(filteredInfo));
};
const send = (type, info) => {
  _baseSend(type, info);
};

export default send;
